package com.alibaba.cloud.base.auth.token;

import com.alibaba.cloud.base.tips.AuthTips;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.framework.domain.ResponseWrapper;
import com.alibaba.framework.exception.ResponseCode;
import com.alibaba.framework.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class OauthCallBackController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OauthCallBackController.class);

    @RequestMapping("/callback")
    public ResponseWrapper oauthCallback(@RequestParam("code") String code, @RequestParam("state") String state) {
        LOGGER.info("获取到CODE：{}, STATE：{}", code, state);

        String gainTokenUrl = "http://localhost:9094/auth/oauth/token";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("redirect_uri", "http://localhost:9092/base/oauth/callback");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("state", state);
        paramMap.put("code", code);

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Basic YWxpX2NsaWVudDphbGlfc2VjcmV0");

        ResponseWrapper responseWrapper = HttpClientUtil.httpPost(gainTokenUrl, paramMap, HttpClientUtil.CONTENT_TYPE.KEY_VALUE, headerMap);
        Object data = responseWrapper.getData();
        LOGGER.info("oauth2回调接口响应：{}", data);
        if (responseWrapper.getCode() == ResponseCode.SUCCESS_CODE) {
            OauthToken oauthToken = JSONObject.parseObject(data + "", OauthToken.class);
            String token = oauthToken.getAccess_token();

            return ResponseWrapper.Success(token);
        } else {
            if((data + "").contains("invalid_grant")) {
                return ResponseWrapper.Fail(AuthTips.INVALID_AUTHORIZATION_CODE, data);
            }
            return ResponseWrapper.Fail(data);
        }
    }
}
